const url = require("url"),
	path = require("path"),
	hx = require('./huanxin.js').init(),
	fs = require("fs"),
	userDB = require("./userDB.js").init();
/*
 * 接收http路由
 * */
exports.init = function() {
	return new httpRoute()
}
/*
 
 * 处理对象
 * */
class httpRoute {
	constructor() {

//		this.httpAPIJSON = JSON.parse(fs.readFileSync('./JSON/httpAPI.json'));
	}

	//有http请求
	httpRequest(req, res) {
		if(req.url.indexOf('/api') >= 0) {
			this.visitAPI(req, res)
			return;
		}
		if(req.url == '/file') { //上传接口
			this.visitFile(req, res)
			return
		}
		var pathname = __dirname + url.parse(req.url).pathname;

		if(path.extname(pathname) == "") { //没有文件后缀
			pathname += "/";
		}
		if(pathname.charAt(pathname.length - 1) == "/") { //以/结尾
			pathname += "index.html";
		}
		if(path.isAbsolute(pathname)) {
			this.visitWeb(req, res, pathname)
		} else {
			res.writeHead(404, {
				"Content-Type": "text/html"
			});
			res.end("<h1>404 Not Found</h1>");
		}
	}

	//文件访问文件目录
	visitFile(req, res) {
		//判断文件上下穿类型
		console.log('文件上传');
		// 设置接收数据编码格式为 UTF-8  
		req.setEncoding('utf-8');
		var postData = ""; //POST & GET ： name=zzl&email=zzl@sina.com  
		// 数据块接收中  
		req.addListener("data", function(postDataChunk) {
			postData += postDataChunk;
		});
		// 数据接收完毕，执行回调函数  
		req.addListener("end", function() {
			//			var params = querystring.parse(postData); //GET & POST  ////解释表单数据部分{name="zzl",email="zzl@sina.com"}  
			var params = postData;
			var baseArray = params.split(',');
			var baseStr = baseArray[1]
			console.log('文件头--' + baseArray[0])
			var suffix = baseArray[0].split(';');
			var suffix = suffix[0].split('/');
			var suffix = suffix[1];
			console.log(suffix);
			var filePath = 'file/' + (new Date().getTime()) + '.' + suffix
			base64_decode(baseStr, filePath)
			res.writeHead(200, {
				"Content-Type": "text/plain;charset=utf-8"
			});
			res.end(filePath);
		});
	}
	//访问api数据
	visitAPI(req, res) {
		let apiURL = req.url.toString();
		console.log('api请求' + apiURL);
		apiURL = apiURL.replace('/api/', ' ');
		//匹配路由
		const cellback = (data) => {
			console.log('返回数据' + data)
			res.writeHead(200, {
				"Content-Type": "application/json"
			});
			res.end(data);
		}
		req.setEncoding('utf-8');
		var postData = ""; //POST & GET ： name=zzl&email=zzl@sina.com  
		// 数据块接收中  
		req.addListener("data", function(postDataChunk) {
			postData += postDataChunk;
		});
		// 数据接收完毕，执行回调函数  
		req.addListener("end", function() {
			//var params = querystring.parse(postData); //GET & POST  ////解释表单数据部分{name="zzl",email="zzl@sina.com"}  
			console.log(postData)
			const data = postData
			try {
				eval('LYRoute.' + apiURL + '(data, cellback)');

			} catch(e) {
				console.log(e.name + ": " + e.message);
				res.writeHead(404, {
					"Content-Type": "text/html"
				});
				res.end("没有找到对应路径");
			}
		});
	}
	//访问web文件
	visitWeb(req, res, pathname) {
		console.log('请求path---' + path.extname(pathname))
		switch(path.extname(pathname)) {
			case ".html":
				res.writeHead(200, {
					"Content-Type": "text/html"
				});
				break;
			case ".js":
				res.writeHead(200, {
					"Content-Type": "text/javascript"
				});
				break;
			case ".css":
				res.writeHead(200, {
					"Content-Type": "text/css"
				});
				break;
			case ".gif":
				res.writeHead(200, {
					"Content-Type": "image/gif"
				});
				break;
			case ".jpg":
				res.writeHead(200, {
					"Content-Type": "image/jpeg"
				});
				break;
			case ".png":
				res.writeHead(200, {
					"Content-Type": "image/png"
				});
				break;
			default:
				res.writeHead(200, {
					"Content-Type": "application/octet-stream"
				});
		}
		fs.readFile(pathname, function(err, data) {
			res.end(data);
		});
	}

	//路径错误
	err404(res) {
		res.writeHead(404, {
			"Content-Type": "text/html"
		});
		res.end("没有找到对应路径");
	}

}

function base64_decode(base64str, file) {
	// create buffer object from base64 encoded string, it is important to tell the constructor that the string is base64 encoded
	var bitmap = new Buffer(base64str, 'base64');
	// write buffer to file
	fs.writeFileSync(file, bitmap);
}

/*
 * 用来分配路由
 * */
class route {
	//注册逻辑
	signIn(data, callback) {
		console.log('登录协议触发--' + data);
		data = JSON.parse(data)
		const {username, password,nickname} = data
		console.log(nickname)
		//向环信注册
		hx.signIn(data, (data)=>{
			if (data.err != 0) {
				data['msg'] = 'zhang hao chong fu'
				callback && callback(JSON.stringify(data));
			}else {
				userDB.foundUser(username, password, nickname, function () {
					callback && callback(JSON.stringify(data));
				}, ()=>{callback && callback(JSON.stringify({err: 2}))});
			}
		});
		//成功向本地注册
	}
}
const LYRoute = new route();


